/**
 * 收件人数据预览组件
 */
import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Tag,
  Space,
  Button,
  Select,
  Alert,
  Tooltip,
  Modal,
  Descriptions,
} from 'antd';
import {
  EyeOutlined,
  UserOutlined,
  MailOutlined,
  DatabaseOutlined,
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Option } = Select;

interface RecipientData {
  email: string;
  name?: string;
  variables?: Record<string, any>;
}

interface RecipientDataPreviewProps {
  recipients: RecipientData[];
  sendMode: 'batch' | 'personalized';
  onRecipientSelect?: (recipient: RecipientData) => void;
  maxPreviewCount?: number;
}

const RecipientDataPreview: React.FC<RecipientDataPreviewProps> = ({
  recipients,
  sendMode,
  onRecipientSelect,
  maxPreviewCount = 10,
}) => {
  const [selectedRecipient, setSelectedRecipient] = useState<RecipientData | null>(null);
  const [detailVisible, setDetailVisible] = useState(false);
  const [previewRecipients, setPreviewRecipients] = useState<RecipientData[]>([]);

  useEffect(() => {
    // 限制预览数量
    setPreviewRecipients(recipients.slice(0, maxPreviewCount));
  }, [recipients, maxPreviewCount]);

  // 查看收件人详情
  const handleViewDetail = (recipient: RecipientData) => {
    setSelectedRecipient(recipient);
    setDetailVisible(true);
  };

  // 获取变量统计
  const getVariableStats = () => {
    const allVariables = new Set<string>();
    recipients.forEach(recipient => {
      if (recipient.variables) {
        Object.keys(recipient.variables).forEach(key => allVariables.add(key));
      }
    });
    return Array.from(allVariables);
  };

  // 表格列定义
  const columns: ColumnsType<RecipientData> = [
    {
      title: '邮箱地址',
      dataIndex: 'email',
      key: 'email',
      render: (text: string) => (
        <Space>
          <MailOutlined />
          <span>{text}</span>
        </Space>
      ),
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      render: (text: string) => text || '-',
    },
    {
      title: '变量数量',
      key: 'variables',
      render: (_, record: RecipientData) => {
        const variableCount = record.variables ? Object.keys(record.variables).length : 0;
        return (
          <Tag color={variableCount > 0 ? 'blue' : 'default'}>
            {variableCount} 个
          </Tag>
        );
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record: RecipientData) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Button
              type="text"
              icon={<EyeOutlined />}
              onClick={() => handleViewDetail(record)}
            />
          </Tooltip>
          {onRecipientSelect && (
            <Button
              type="text"
              onClick={() => onRecipientSelect(record)}
            >
              选择
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const allVariables = getVariableStats();

  return (
    <div>
      <Card
        title={
          <Space>
            <UserOutlined />
            收件人数据预览
            <Tag color="blue">{recipients.length} 人</Tag>
          </Space>
        }
        size="small"
      >
        {/* 统计信息 */}
        <div style={{ marginBottom: 16 }}>
          <Alert
            message="发送统计"
            description={
              <div>
                <Space wrap>
                  <Tag color="blue">总计: {recipients.length} 人</Tag>
                  <Tag color="green">
                    有姓名: {recipients.filter(r => r.name).length} 人
                  </Tag>
                  <Tag color="orange">
                    有变量: {recipients.filter(r => r.variables && Object.keys(r.variables).length > 0).length} 人
                  </Tag>
                  <Tag color="purple">
                    发送模式: {sendMode === 'batch' ? '批量发送' : '个性化发送'}
                  </Tag>
                </Space>
                {allVariables.length > 0 && (
                  <div style={{ marginTop: 8 }}>
                    <strong>可用变量：</strong>
                    <Space wrap style={{ marginLeft: 8 }}>
                      {allVariables.map(variable => (
                        <Tag key={variable} color="cyan" size="small">
                          {variable}
                        </Tag>
                      ))}
                    </Space>
                  </div>
                )}
              </div>
            }
            type="info"
            showIcon
          />
        </div>

        {/* 收件人表格 */}
        <Table
          columns={columns}
          dataSource={previewRecipients}
          rowKey={(record, index) => `${record.email}-${index}`}
          pagination={false}
          size="small"
          locale={{ 
            emptyText: '暂无收件人数据' 
          }}
        />

        {recipients.length > maxPreviewCount && (
          <div style={{ textAlign: 'center', marginTop: 16, color: '#666' }}>
            仅显示前 {maxPreviewCount} 个收件人，共 {recipients.length} 个收件人
          </div>
        )}
      </Card>

      {/* 收件人详情弹窗 */}
      <Modal
        title={`收件人详情 - ${selectedRecipient?.email}`}
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailVisible(false)}>
            关闭
          </Button>,
        ]}
        width={600}
      >
        {selectedRecipient && (
          <div>
            <Descriptions column={1} bordered>
              <Descriptions.Item label="邮箱地址">
                {selectedRecipient.email}
              </Descriptions.Item>
              <Descriptions.Item label="姓名">
                {selectedRecipient.name || '未设置'}
              </Descriptions.Item>
              <Descriptions.Item label="变量数量">
                {selectedRecipient.variables ? Object.keys(selectedRecipient.variables).length : 0} 个
              </Descriptions.Item>
            </Descriptions>

            {selectedRecipient.variables && Object.keys(selectedRecipient.variables).length > 0 && (
              <div style={{ marginTop: 16 }}>
                <h4>变量详情：</h4>
                <Card size="small">
                  <Descriptions column={1} size="small">
                    {Object.entries(selectedRecipient.variables).map(([key, value]) => (
                      <Descriptions.Item key={key} label={key}>
                        <span style={{ fontFamily: 'Monaco, Consolas, monospace' }}>
                          {typeof value === 'object' ? JSON.stringify(value) : String(value)}
                        </span>
                      </Descriptions.Item>
                    ))}
                  </Descriptions>
                </Card>
              </div>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
};

export default RecipientDataPreview;
